import React, {
    Component,
} from 'react'


import {
    StyleSheet,
    View,
    Platform,
    Text,
    Image,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    DeviceEventEmitter, NativeModules, Dimensions, AsyncStorage
    //Toast
} from 'react-native';
import BasePage from './Component/Common/BasePage';

import PageView from './Component/Common/PageView'
import {Theme, NavigationPage, ListRow, NavigationBar, Label} from 'teaset';

import GeneralMethods from './Component/Common/GeneralMethods'
import CommonStyle from "./Component/CommonStyle";

import ImagePicker from 'react-native-syan-image-picker'
import GetData from "./GetData";

import SQLite from './SQLite';

var sqLite = new SQLite();
var db;

const defaultOptions = {
    imageCount: 1,             // 最大选择图片数目，默认6
    isRecordSelected: false,   // 是否已选图片
    isCamera: true,            // 是否允许用户在内部拍照，默认true
    isCrop: true,             // 是否允许裁剪，默认false, imageCount 为1才生效
    CropW: ~~(width * 0.6),    // 裁剪宽度，默认屏幕宽度60%
    CropH: ~~(width * 0.6),    // 裁剪高度，默认屏幕宽度60%
    isGif: false,              // 是否允许选择GIF，默认false，暂无回调GIF数据
    showCropCircle: true,     // 是否显示圆形裁剪区域，默认false
    circleCropRadius: width / 2, // 圆形裁剪半径，默认屏幕宽度一半
    showCropFrame: true,       // 是否显示裁剪区域，默认true
    showCropGrid: false,       // 是否隐藏裁剪区域网格，默认false
    quality: 90,               // 压缩质量
    enableBase64: false,       // 是否返回base64编码，默认不返回
};
const {RNSyanImagePicker} = NativeModules;

const {width} = Dimensions.get('window');


export default class MytwoPage extends BasePage {


    constructor(props) {
        super(props);
        this.state = {
            ...this.state,
            head: require('./images/head.png'),

            name: '',

        };

    }


    showImagePicker(options, callback) {
        const optionObj = {
            ...defaultOptions,
            ...options
        };
        RNSyanImagePicker.showImagePicker(optionObj, callback)
    }


    componentWillMount() {


        if (!db) {
            db = sqLite.open();
        } else {
            //建表
            sqLite.createTable();
        }

        AsyncStorage.getItem('person',  (error, result)=> {
            if (error) {
                // alert('读取失败')
            } else {
                console.log(result)
                let jsonValue = JSON.parse(result);
                var namestring = jsonValue.name;


                this.setState({
                    name: namestring,

                    head: jsonValue.headurl!=''?{uri: jsonValue.headurl}:require('./images/head.png')

                });


                //查询
                db.transaction((tx) => {
                    tx.executeSql("select * from user  WHERE name=? ", [namestring], (tx, results) => {
                        var len = results.rows.length;


                        for (let i = 0; i < len; i++) {
                            var u = results.rows.item(i);
                            if (u.name == this.state.name) {


                            }

                            //一般在数据查出来之后，  可能要 setState操作，重新渲染页面
                        }

                    });
                }, (error) => {//打印异常信息
                });

            }
        })

    }


    renderNavigationBar() {
        return (
            <NavigationBar
                style={{backgroundColor: 'white',}}

                title={
                    <View style={{
                        flexDirection: 'row',
                        justifyContent: 'center',
                        alignSelf: 'center',

                    }}>
                        <Text style={{
                            fontSize: 20,
                            color: '#333333'
                        }}>个人信息</Text>
                    </View>}

                leftView={<TouchableOpacity
                    onPress={() => {


                        this.navigator.pop();


                        // DeviceEventEmitter.emit('my', {text: '刷新'})

                    }}
                >
                    <Image style={{width: 15, height: 15, marginLeft: 20}} source={require('./images/btn_back.png')}/>

                </TouchableOpacity>}
                // rightView={<TouchableOpacity
                //     onPress={() => {
                //
                //     }}
                // >
                //     <Image style={{width: 22, height: 22, marginRight: 20}} source={require('./images/add.png')}/>
                //
                // </TouchableOpacity>}
            />

        );
    }


    _onChangeText(inputData) {
        console.log("输入的内容", inputData);
        //把获取到的内容，设置给showValue
        // this.setState({showValue: inputData});
    }

    renderPage() {


        return (
            <View style={{
                flexDirection: 'column',
                marginTop: 46,
                flex: 1
            }}>
                <View style={{height: 10, backgroundColor: '#f2f2f2'}}/>

                <TouchableOpacity
                    onPress={() => {
                        this.showImagePicker(defaultOptions, (err, selectedPhotos) => {
                            if (err) {
                                //选择失败
                                return
                            }


                            // this.setState({
                            //     name: this._get() != null ? this._get() : ''
                            // });


                            let url = selectedPhotos[0].uri

                            let source = {uri: url};

                            //   You can also display the image using data:
                            //  let source = { uri: 'data:image/jpeg;base64,' + response.data };


                            AsyncStorage.getItem('person', function (error, result) {
                                if (error) {
                                    // alert('读取失败')
                                } else {
                                    console.log(result)
                                    let jsonValue = JSON.parse(result);
                                    var namestring = jsonValue.name;


                                    var updateDataSQL = 'UPDATE  USER' + ' SET HEADURL = ? WHERE NAME = ?';


                                    db.transaction(function (context) {
                                            context.executeSql(updateDataSQL, [url, namestring]);
                                        },
                                        function (error) {
                                            alert('更新数据失败' + error.message)
                                        }, function () {
                                            console.log('更新数据成功');
                                            // alert('头像更换成功')
                                            DeviceEventEmitter.emit("my",'更换头像');
                                        });


                                    var person = {
                                        name: namestring,
                                        islond: 1,
                                        headurl:url
                                    }
                                    var jsonStr = JSON.stringify(person)


                                    AsyncStorage.setItem('person', jsonStr, function (error) {
                                        if (error) {
                                            // alert('存储失败')
                                        } else {
                                            // alert('存储完成')
                                        }
                                    })


                                }
                            })
//
                            this.setState({
                                head: source
                            })

                        })

                    }}
                >
                    <View style={{
                        height: 90,
                        backgroundColor: '#FFFFFF',
                        justifyContent: 'center'
                    }}>
                        <Image
                            resizeMode={'stretch'} style={{
                            width: 70, height: 70, borderRadius: 35,
                            marginLeft: 20
                        }}
                            source={this.state.head}/>

                        <Image
                            resizeMode={'stretch'} style={{
                            position: 'absolute',
                            right: 18,
                            width: 15, height: 15,
                        }}
                            source={require('./images/go.png')}/>


                    </View>
                </TouchableOpacity>


                <View style={{height: 10, backgroundColor: '#f2f2f2'}}/>
                <View style={{
                    height: 40,

                    flexDirection: 'row',
                    alignItems: 'center',
                    backgroundColor: '#FFFFFF',
                }}>
                    <Text style={{marginLeft: 15}}>姓名</Text>
                    <TextInput
                        value={this.state.name}
                        placeholder="请输入名字"
                        editable={true}//是否可编辑
                        style={styles.inputStyle}//input框的基本样式
                        onChangeText={this._onChangeText}//输入框改变触发的函数
                    />


                </View>


                <View style={{height: 10, backgroundColor: '#f2f2f2'}}/>
            </View>
        );

    }

    componentDidMount() {
        this.setState({
            refreshing: true,
        })
        setTimeout(() => {
            this.setState({
                refreshing: false,
            })
        }, 3000)
    }


}
let screenW = Dimensions.get('window').width;
let screenH = Dimensions.get('window').height;
// iPhoneX
const X_WIDTH = 375
const X_HEIGHT = 812
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginBottom: Platform.OS === 'ios' &&
        ((screenH === X_HEIGHT && screenW === X_WIDTH) ||
            (screenH === X_WIDTH && screenW === X_HEIGHT)) ? 34 : null
    },
    title: {
        flexDirection: 'row',
        width: CommonStyle.screenwidth
    },
    title_left: {
        marginLeft: 15,
        alignSelf: 'center'
    },

    title_right: {
        fontSize: 14,
        color: CommonStyle.color_deep_red,
        marginRight: 15,
        alignSelf: 'center'
    },
    button: {
        height: 29,
        width: CommonStyle.screenwidth / 5,
        flexDirection: 'row', justifyContent: 'flex-end',
        borderBottomLeftRadius: 5,
        borderTopLeftRadius: 5,
    },
    button2: {
        height: 29,
        width: CommonStyle.screenwidth / 5,
        flexDirection: 'row',
        borderTopRightRadius: 5,
        borderBottomRightRadius: 5,
    },

    tab1Style: {

        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'white',

    },
    tab2Style: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#1196DB',

    },
    tab3Style: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#1196DB',
    },
    tab4Style: {
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: 'white',
    },
    newText1Style: {
        fontSize: 11,
        color: '#1196DB'
    },
    newText2Style: {
        fontSize: 11,
        color: 'white'
    }, inputStyle: {
        flex: 1,
        marginRight: 15,
        marginLeft: 5,
    }
});
